package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;


    /**
     * 查询所有秒杀商品数据
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        //调用服务层方法
        List<SeckillGoods> list = seckillGoodsService.findAll();
        //放回数据
        return Result.ok(list);
    }

    /**
     * 根据skuId 来获取秒杀详情
     *
     * @param skuId
     * @return
     */
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId) {
        //  调用服务层方法
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoodsById(skuId);
        //返回数据
        return Result.ok(seckillGoods);

    }


    //  获取下单码.
    //  /api/activity/seckill/auth/getSeckillSkuIdStr/{skuId}
    //  auth: 必须处于登录状态.
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        //  用户Id
        String userId = AuthContextHolder.getUserId(request);
        //获取当前秒杀对象
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoodsById(skuId);
        //判断
        if (seckillGoods != null) {
            //判断时间 当前系统时间，在开始时间之后，结束之间之前
            Date currentTime = new Date();
            if (DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //生成下单码
                String skuIdStr = MD5.encrypt(userId);
                //返回数据，返回下单码
                return Result.ok(skuIdStr);
            }
        }
        //返回失败
        return Result.fail().message("获取下单码失败");
    }




}
